//
//  LBFrameFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 4/8/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBFrameFilter.h"
#include "LBGraphics.h"

char fShaderStrFrame[] = ""
"precision mediump float;"

"varying vec2 vtexCoor;"
"varying vec4 vposition;"
"uniform sampler2D texture;"
"uniform sampler2D texture2;"
"uniform float opacity;"
"uniform vec4 frameSize;"       // x, y, z, w is x, y, width, height
"uniform vec4 textureSize;"


"void main()"
"{"

"    float xTexCoor1 = (vtexCoor.x-textureSize.x)/textureSize.z;"
"    float yTexCoor1 = (vtexCoor.y-textureSize.y)/textureSize.w;"

"    lowp vec4 textureColor;"
"    if(vtexCoor.x > textureSize.x && vtexCoor.x < textureSize.x + textureSize.z && vtexCoor.y > textureSize.y && vtexCoor.y < textureSize.y + textureSize.w){"
"      textureColor = texture2D(texture, vec2(xTexCoor1, yTexCoor1));"
"   }"
"   else textureColor = vec4(1.0, 1.0, 1.0, 1.0);"

"    float xTexCoor2 = (vtexCoor.x-frameSize.x)/frameSize.z;"
"    float yTexCoor2 = (vtexCoor.y-frameSize.y)/frameSize.w;"

"    if(vtexCoor.x > frameSize.x && vtexCoor.x < frameSize.x + frameSize.z && vtexCoor.y > frameSize.y && vtexCoor.y < frameSize.y + frameSize.w){"
"       lowp vec4 blendColor = texture2D(texture2, vec2(xTexCoor2, yTexCoor2));"
"       textureColor = mix(textureColor, blendColor, opacity*blendColor.a);"
"   }"
"    gl_FragColor = textureColor;"
"}";

LBFrameFilter::LBFrameFilter(){
    init(0, fShaderStrFrame);
    LBGraphics::getInstance()->useProgram(program);
    opacityUniform = program->uniformIndex("opacity");
    frameSizeUniform = program->uniformIndex("frameSize");
    textureSizeUniform = program->uniformIndex("textureSize");
    setOpactiy(1.0f);
    setTextureSize(0.0f, 0.0f, 1.0f, 1.0f);
    setFrameSize(0.0f, 0.0f, 1.0f, 1.0f);
}

void LBFrameFilter::setFrameSize(float x, float y, float width, float height){
    this->xF = x;
    this->yF = y;
    this->widthF = width;
    this->heightF = height;
    LBGraphics::getInstance()->useProgram(program);
    glUniform4f(frameSizeUniform, x, y, width, height);
}

void LBFrameFilter::setTextureSize(float x, float y, float width, float height){
    this->xT = x;
    this->yT = y;
    this->widthT = width;
    this->heightT = height;
    LBGraphics::getInstance()->useProgram(program);
    glUniform4f(textureSizeUniform, x, y, width, height);
}

void LBFrameFilter::setFrameTexture(LBTexture* frameTexture){
    setTexture2(frameTexture);
}